package com.heima.media.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.WmSensitiveDto;
import com.heima.media.entity.WmSensitive;
import com.heima.media.service.IWmSensitiveService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 敏感词信息表 前端控制器
 * </p>
 *
 * @author Wq
 * @since 2022-10-12
 */
@RestController
@RequestMapping("/api/v1/sensitive")
@Api(tags = "敏感词信息表接口")
@CrossOrigin
public class WmSensitiveController {

    @Autowired
    private IWmSensitiveService wmSensitiveService;

    /**
     * 读取excel文件
     *
     * @param file 文件
     * @return {@code ResponseResult}
     * @throws Exception 异常
     */
    @PostMapping("upload")
    public ResponseResult upload(MultipartFile file) throws Exception {

        EasyExcel.read(file.getInputStream(), WmSensitive.class, new PageReadListener<WmSensitive>(dataList -> {
            for (WmSensitive wmSensitive : dataList) {
                //判断这个敏感词是否在数据库已经存在
                LambdaQueryWrapper<WmSensitive> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(WmSensitive::getSensitives, wmSensitive.getSensitives());
                int count = wmSensitiveService.count(wrapper);
                if (count <= 0) {
                    wmSensitive.setCreatedTime(new Date());
                    wmSensitiveService.save(wmSensitive);
                }
            }
        })).sheet().doRead();

        return ResponseResult.okResult();
    }

    /**
     * 导出excel文件
     *
     * @param response 响应
     * @return {@code ResponseResult}
     * @throws Exception 异常
     */
    @PostMapping("download")
    public ResponseResult download(HttpServletResponse response) throws Exception {
        ServletOutputStream outputStream = response.getOutputStream();
        //文件下载 一个流  两个头
        // 输出流
        //一个响应头 文件打开方式  默认浏览器打开
        //一个文件的mime类型
        response.setHeader("content-disposition", "attachment;filename=WmSensitive.xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        EasyExcel.write(outputStream, WmSensitive.class)
                .sheet("敏感词")
                .doWrite(() -> {
                    //查询数据
                    List<WmSensitive> list = wmSensitiveService.list();
                    return list;
                });

        return ResponseResult.okResult();
    }

    /**
     * 敏感词列表查询
     *
     * @param
     * @return {@link ResponseResult}
     */
    @PostMapping("list")
    public ResponseResult pageByCondition(@RequestBody WmSensitiveDto dto) {
        return wmSensitiveService.pageByCondition(dto);
    }

    /**
     * 保存敏感词
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @PostMapping
    public ResponseResult saveSensitives(@RequestBody WmSensitiveDto dto) {
        if (StrUtil.isBlank(dto.getSensitives())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据敏感词查询
        LambdaQueryWrapper<WmSensitive> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmSensitive::getSensitives, dto.getSensitives());
        WmSensitive wmSensitive = wmSensitiveService.getOne(wrapper);
        if (ObjUtil.isNotNull(wmSensitive)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        wmSensitive = new WmSensitive();
        wmSensitive.setSensitives(dto.getSensitives());
        wmSensitive.setCreatedTime(new Date());
        wmSensitiveService.save(wmSensitive);
        return ResponseResult.okResult();
    }

    /**
     * 修改敏感词
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @PutMapping
    public ResponseResult updateSensitives(@RequestBody WmSensitiveDto dto) {
        if (StrUtil.isBlank(dto.getSensitives()) || ObjUtil.isNull(dto.getId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //根据敏感词查询  是否已近存在
        LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmSensitive::getSensitives, dto.getSensitives());
        WmSensitive wmSensitive = wmSensitiveService.getOne(queryWrapper);
        if (ObjUtil.isNotNull(wmSensitive)) {
            //排除掉是自己的情况
            if (!dto.getId().equals(wmSensitive.getId())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
            }
        }
        //名称不存在在修改
        wmSensitive = new WmSensitive();
        wmSensitive.setSensitives(dto.getSensitives());
        wmSensitive.setId(dto.getId());
        wmSensitiveService.updateById(wmSensitive);
        return ResponseResult.okResult();
    }

    /**
     * 通过id删除敏感词
     *
     * @param id id
     * @return {@link ResponseResult}
     */
    @DeleteMapping("/{id}")
    public ResponseResult deleteById(@PathVariable Integer id) {
        wmSensitiveService.removeById(id);
        return ResponseResult.okResult();
    }

}
